//
//  NSString+file.m
//  weibo
//
//  Created by apple on 13-8-28.
//  Copyright (c) 2013年 itcast. All rights reserved.
//

#import "NSString+File.h"
#import <CommonCrypto/CommonDigest.h>
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <CommonCrypto/CommonCryptor.h>


@implementation NSString (File)

- (BOOL)isUrlString {
  NSString *emailRegex = @"[a-zA-z]+://.*";
  NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  return [emailTest evaluateWithObject:self];

}
//字符串拼接
- (NSString *)filenameAppend:(NSString *)append
{
    // 1.获取没有拓展名的文件名
    NSString *filename = [self stringByDeletingPathExtension];
    
    // 2.拼接append
    filename = [filename stringByAppendingString:append];
    
    // 3.拼接拓展名
    NSString *extension = [self pathExtension];
    
    // 4.生成新的文件名
    return [filename stringByAppendingPathExtension:extension];
}

+ (BOOL)isCodeValid:(NSString *)code
{
    if (code.length >= 6 && code.length <=32) {
        
        return YES;
    }
    return NO;
}
//删除NSString的最后一个字符
+(NSString*) removeLastOneChar:(NSString*)origin
{
    NSString* cutted;
    if([origin length] > 0){
        cutted = [origin substringToIndex:([origin length]-1)];// 去掉最后一个","
    }else{
        cutted = origin;
    }
    return cutted;
}

//用户名验证
+ (BOOL)isUserNameValid:(NSString*)name
{
    NSString* regex = @"^\\w{4,20}$";
    NSPredicate *regexname = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if ([regexname evaluateWithObject:name] == YES) {
        return YES;
    } else {
        return NO;
    }
}



//用户密码验证
+ (BOOL)isUserPasswordValid:(NSString*)password
{
    NSString* regex = @"^([\\w\\d]){6,20}$";
    NSPredicate *regexpassword = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    if ([regexpassword evaluateWithObject:password] == YES) {
        return YES;
    } else {
        return NO;
    }
}

//电子邮箱验证
+ (BOOL)isEmailValid:(NSString*)email{
//    NSString* regex = @"^\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
    NSString* regex = @"^[a-z0-9]*([-+.'][a-z0-9]*)*@[a-z0-9]*([-.][a-z0-9]*)*\\.[a-z0-9]*([-.][a-z0-9]*)*$";
    NSPredicate *regexemail = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    if ([regexemail evaluateWithObject:email] == YES) {
        return YES;
    } else {
        return NO;
    }
}

+ (BOOL)isAustraliaNumber:(NSString *)phone
{
//    NSString *mobileregex = @"^((1(3[0-9]|5[0-9]|8[0-9])|04)\\d{8})$";
    NSString *mobileregex = @"^^(((13[0-9]{1})|159|153|04)\\d{8})$";

    NSPredicate *regexmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mobileregex];
    
    if ([regexmobile evaluateWithObject:phone] == YES) {
        return YES;
    }else {
        return NO;
    }
}



//身份证号码
+(BOOL)checkIdentityCardNo:(NSString*)identityString
{
    if (identityString.length != 18) return NO;
    // 正则表达式判断基本 身份证号是否满足格式
    NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityStringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    //如果通过该验证，说明身份证格式正确，但准确性还需计算
    if(![identityStringPredicate evaluateWithObject:identityString]) return NO;
    
    //** 开始进行校验 *//
    //将前17位加权因子保存在数组里
    NSArray *idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
    
    //这是除以11后，可能产生的11位余数、验证码，也保存成数组
    NSArray *idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
    
    //用来保存前17位各自乖以加权因子后的总和
    NSInteger idCardWiSum = 0;
    for(int i = 0;i < 17;i++) {
        NSInteger subStrIndex = [[identityString substringWithRange:NSMakeRange(i, 1)] integerValue];
        NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
        idCardWiSum+= subStrIndex * idCardWiIndex;
    }
    
    //计算出校验码所在数组的位置
    NSInteger idCardMod=idCardWiSum%11;
    //得到最后一位身份证号码
    NSString *idCardLast= [identityString substringWithRange:NSMakeRange(17, 1)];
    //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
    if(idCardMod==2) {
        if(![idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"]) {
            return NO;
        }
    }
    else{
        //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
        if(![idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]]) {
            return NO;
        }
    }
    return YES;
}

//过滤数字
-(BOOL)isNumber
{
    NSString *match=@"(^[0-9]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:self];
}

-(BOOL)isChinese
{
    NSString *match=@"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:self];
}

- (BOOL)includeChinese
{
    for(int i=0; i< [self length];i++)
    {
        int a =[self characterAtIndex:i];
        if( a >0x4e00&& a <0x9fff){
            return YES;
        }
    }
    return NO;
}

- (BOOL)isEnglishNum
{
    NSString *match=@"(^[a-zA-Z0-9]*$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:self];
}

//密码强度验证
+ (NSString *)checkPasswordStrength:(NSString*)password
{
    //强密码正则表达式
    NSString *strongregex = @"^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$";
    NSPredicate *regexstrong = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", strongregex];
    //中密码正则表达式
    NSString *mediumregex = @"^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$";
    NSPredicate *regexmedium = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mediumregex];
    
    
    if ([regexstrong evaluateWithObject:password] == YES) {
        return @"strong";
    }else if ([regexmedium evaluateWithObject:password] == YES) {
        return @"normal";
    }else {
        return @"weak";
    }
    
    return nil;
}

//密码强度验证
+ (NSString *)checkPasswordStrength2:(NSString*)password
{
    int matchCount=0;
    BOOL hasDigit=FALSE;//是否存在数字
    BOOL hasLetter=FALSE;//是否存在小写字符
    BOOL hasBigLetter=FALSE;//是否存在大写字符
    BOOL hasSpecial=FALSE;//是否存在特殊字符
    //正则表达式（包含 数字、字母、特殊字符）
    NSString *regex = @"^[0-9a-zA-Z_]\\w{5,32}$";
    NSPredicate *regexvalid = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    //只包含数字的密码验证(6-32)
    NSString *digitregex = @"\\d+";
    NSPredicate *regexdigit = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", digitregex];
    //只包含小写字母的密码验证(6-32)
    NSString *letterregex = @"[a-z]+";
    NSPredicate *regexletter = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", letterregex];
    //只包含大写字母的密码验证(6-32)
    NSString *bigletterregex = @"[A-Z]+";
    NSPredicate *regexbigletter = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", bigletterregex];
    //只包含特殊字符_的密码验证(6-32)
    NSString *specialregex = @"[_]+";
    NSPredicate *regexspecial = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", specialregex];
    
    //检索每个字符
    for (int i=1; i<=password.length; i++) {
        NSLog(@"i:%@",[[password substringToIndex:i] substringFromIndex:i-1]);
        NSString *indexPsd=[[password substringToIndex:i] substringFromIndex:i-1];
        if ([regexdigit evaluateWithObject:indexPsd] == YES) {
            hasDigit=TRUE;
        }if ([regexletter evaluateWithObject:indexPsd] == YES) {
            hasLetter=TRUE;
        }if ([regexbigletter evaluateWithObject:indexPsd] == YES) {
            hasBigLetter=TRUE;
        }if ([regexspecial evaluateWithObject:indexPsd] == YES) {
            hasSpecial=TRUE;
        }
    }
    
    
    
    if (hasDigit) {
        matchCount+=1;
    }if (hasLetter) {
        matchCount+=1;
    }if (hasBigLetter) {
        matchCount+=1;
    }if (hasSpecial) {
        matchCount+=1;
    }
    NSLog(@"matchcount:%d",matchCount);
    
    if (![regexvalid evaluateWithObject:password] == YES) {
        return @"unvalid";
    }else if (matchCount==1) {
        return @"low";
    }else if (matchCount==2||matchCount==3) {
        return @"medium";
    }else if (matchCount==4) {
        return @"high";
    }
    
    return nil;
}

//URL转码
- (NSString *)URLEncodeString
{
    NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR("+ $ , # [ ]"), kCFStringEncodingUTF8));
    return result;
}

//URL解码
- (NSString *)URLDecodeString
{
    NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)self, CFSTR(""), kCFStringEncodingUTF8));
    return result;
}

//将NSString 转换成 NSarray NSdictionay
-(id)JSONValue
{
    NSData* data = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSError* error = nil;
    id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    if (error != nil) return nil;
    return result;
}

+ (NSString *)stringWithDict:(NSDictionary *)dict
{
    NSError *error = nil;
    NSData *jsondata = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    if(error){
        return nil;
    }
    NSString *str = [[NSString alloc]initWithData:jsondata encoding:NSUTF8StringEncoding];
    str=[@"[" stringByAppendingFormat:@"%@%@",str,@"]"];
    
    return str;
}

+ (NSString *)stringWithArray:(NSArray *)array
{
    NSError *error = nil;
    NSData *jsondata = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
    if(error){
        return nil;
    }
    NSString *str = [[NSString alloc]initWithData:jsondata encoding:NSUTF8StringEncoding];
    return str;
}


////将NSarray NSdictionay 转换成 NSString
//-(NSData*)JSONString
//{
//    NSError* error = nil;
//    id result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error];
//    if (error != nil) return nil;
//    return result;
//}



+ (NSString *)getTenUuids
{
    NSMutableString *uuidTmp = [NSMutableString stringWithFormat:@"%@",[UIDevice currentDevice].identifierForVendor];
    NSString *uuid = [[NSString alloc] init];
    if ([uuidTmp length] >10) {
        uuid =[uuidTmp substringToIndex:10];
    }
    return uuid;
    
}

+ (NSString *)getCurrentDate
{
    NSDate *date=[NSDate date];
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *curDate=[NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
    return curDate;
}

+ (NSString *)getCurrentDate2
{
    NSDate *date=[NSDate date];
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *curDate=[NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
    
    return curDate;
}

+ (NSString *)getDateString:(NSDate *)date
{
    NSDateFormatter *dateF = [NSDateFormatter new];
    dateF.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
    return [dateF stringFromDate:date];
}
+ (NSString *)getDateString2
{
    NSDate *date=[NSDate date];
    NSDateFormatter *dateF = [NSDateFormatter new];
    dateF.dateFormat = @"yyyy-MM-dd";
    return [dateF stringFromDate:date];
}
+ (NSString *)getDateString3
{
    NSTimeInterval timeS = 6*24*60*60;
    NSDate *currentDate = [NSDate date];
    NSDate  *endate = [currentDate initWithTimeIntervalSinceNow:-timeS];
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr = [formatter stringFromDate:endate];
    return dateStr;
}


+ (NSString *)getCurrentYearString
{
    NSDate *date=[NSDate date];
    NSDateFormatter *dateF = [NSDateFormatter new];
    dateF.dateFormat = @"yyyy";
    
    
    return [dateF stringFromDate:date];
}
+ (NSString *)getCurrentMounthString
{
    NSDate *date=[NSDate date];
    NSDateFormatter *dateF = [NSDateFormatter new];
    dateF.dateFormat = @"MM";
    
    return [dateF stringFromDate:date];
}
+ (NSString *)getCurrentDataString
{
    NSDate *date=[NSDate date];
    NSDateFormatter *dateF = [NSDateFormatter new];
    dateF.dateFormat = @"dd";
    
    return [dateF stringFromDate:date];
}

+ (void)getBgnYM:(NSString *__autoreleasing *)bgnYM andEndYM:(NSString *__autoreleasing *)endYM containDay:(BOOL)contain
{
    NSDate *endDate=[NSDate date];
    NSInteger interval = - 365 / 2 * 24 * 60 * 60;
    NSDate *bgnDate = [NSDate dateWithTimeIntervalSinceNow:interval];
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:[NSString stringWithFormat:@"yyyy-MM%@", contain ? @"-dd": @""]];
    *endYM = [NSString stringWithFormat:@"%@",[formatter stringFromDate:endDate]];
    *bgnYM = [NSString stringWithFormat:@"%@",[formatter stringFromDate:bgnDate]];
}

+(BOOL)isBankNumValid:(NSString*)num
{
    NSString *mobileregex = @"^[\\d]{16,19}";
    NSPredicate *regexmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mobileregex];
    if([regexmobile evaluateWithObject:num]){
        
        return YES;
    }else{
        return NO;
    }
}

+(NSString *)getCurrentTime
{
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    //NSTimeZone *currentZone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]];
    NSString *outStr=[NSString stringWithFormat:@"%@",[formatter stringFromDate:[NSDate date]]];
    return outStr;
    
}
+(NSString *)getCurrentTime2
{
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm:ss"];
    //NSTimeZone *currentZone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]];
    NSString *outStr=[NSString stringWithFormat:@"%@",[formatter stringFromDate:[NSDate date]]];
    return outStr;
}
+(NSString *)getCurrentTime3
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *now;
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags =  NSCalendarUnitWeekday ;
    now=[NSDate date];
    comps = [calendar components:unitFlags fromDate:now];
    NSArray *weekArray = @[@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六"];
    NSInteger weekdaynum = [comps weekday];
    return weekArray[weekdaynum];
}
//获取交易日期
+ (NSString *)transDate
{
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMdd"];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]];
    NSString *outStr=[NSString stringWithFormat:@"%@",[formatter stringFromDate:[NSDate date]]];
    return outStr;
}

//获取交易流水号 生成规则 02+yyyymmddhhmmss+8位随机数
+ (NSString *)serialNo
{
    //十四位时间
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddhhmmss"];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]];
    NSString *nowDateStr=[NSString stringWithFormat:@"%@",[formatter stringFromDate:[NSDate date]]];
    
    //8位随机数
    int randNum = arc4random()%89999999+10000000;
    
    NSString *serialNO = [NSString stringWithFormat:@"%@%@%d",@"02",nowDateStr,randNum];
    
    return serialNO;
    
}

+ (UIImage *)saveTempFileFromUrlString:(NSString *)urlString
{
    NSArray *array = [urlString componentsSeparatedByString:@"?id="];
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"picture"];
    
    NSFileManager *fileM = [NSFileManager defaultManager];
    if (![fileM fileExistsAtPath:filePath]) {
        
        [fileM createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    //判断当前文件夹中是否已经有缓存
    NSString *fileName = [filePath stringByAppendingString:[NSString stringWithFormat:@"/%@", array[1]]];
    
    if ([fileM fileExistsAtPath:fileName]) {
        
        return [UIImage imageWithContentsOfFile:fileName];
    }
    
    //用网络加载
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
    
    [data writeToFile:fileName atomically:YES];
    
    return [UIImage imageWithData:data];
    
}

+ (BOOL)checkCodeValid:(NSString *)code
{
    BOOL success = [code isNumber];
    if (code.length != 6) {
        
        success = NO;
    }
    
    return success;
}

+ (NSString *)xmlstringWithDict:(NSDictionary *)dict
{
    NSMutableString *xmlStr = [[NSMutableString alloc]init];
    [xmlStr appendString:@"<?xml version='1.0' encoding='utf-8' standalone='yes'?>\n"];
    [xmlStr appendString:@"<tree>"];
    NSArray *keys  = dict.allKeys;
    NSArray *values = dict.allValues;
    for (int i = 0 ; i<keys.count; i++) {
        NSString *keyStr = keys[i];
        NSString *valueStr = values[i];
        [xmlStr appendFormat:@"<%@>",keyStr];
        [xmlStr appendString:valueStr];
        [xmlStr appendFormat:@"</%@>",keyStr];
    }
    [xmlStr appendString:@"</tree>"];
    
    return xmlStr;
}

+ (NSString *)xmlstringWithDict:(NSDictionary *)dict attributes:(NSArray *)attArr
{
    NSMutableString *xmlStr = [[NSMutableString alloc]init];
    [xmlStr appendString:@"<?xml version='1.0' encoding='utf-8' standalone='yes'?>\n"];
    [xmlStr appendString:@"<tree>"];
    NSArray *keys  = dict.allKeys;
    NSArray *values = dict.allValues;
    for (int i = 0 ; i<keys.count; i++) {
        NSString *keyStr = keys[i];
        NSString *valueStr = values[i];
        [xmlStr appendFormat:@"<%@>",keyStr];
        [xmlStr appendString:valueStr];
        [xmlStr appendFormat:@"</%@>",keyStr];
    }
    for (NSDictionary *attDict in attArr) {
        NSString *node = [attDict objectForKey:@"node"];
        NSString *text = [attDict objectForKey:@"text"];
        NSString *attKey = [attDict objectForKey:@"attkey"];
        NSString *attValue = [attDict objectForKey:@"attvalue"];
        [xmlStr appendFormat:@"<%@ %@=\"%@\">",node,attKey,attValue];
        [xmlStr appendString:text];
        [xmlStr appendFormat:@"</%@>",node];
    }
    
    [xmlStr appendString:@"</tree>"];
    
    
    return xmlStr;
}

- (NSString *)subCharStringToIndex:(NSInteger)index
{
    NSInteger i = 0;
    if(self){
        
        for (; i < index; i++){
            
            NSRange range=NSMakeRange(i,1);
            
            NSString *subString=[self substringWithRange:range];
            
            const char *cString=[subString UTF8String];
            
            if (strlen(cString)==3){
                NSLog(@"昵称是汉字");
                index -= 2;
            }
            else if (strlen(cString) == 2) {
                
                NSLog(@"昵称是奇怪的字母");
                index--;
            }
        }
    }
    
    return [self substringToIndex:i];
}

- (NSString *)documentAppend
{
    NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
    return [doc stringByAppendingPathComponent:self];
}
- (NSString *)encryptionPassword
{
    return [[NSString stringWithFormat:@"%@ywkj",[self md5]] md5];
}
- (NSString *)md5
{
    const char *cStr = [self UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), digest );
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return output;
}

+ (NSString *)encodeToPercentEscapeString:(NSString *)input
{
    NSString *outputStr = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)input,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    return outputStr;
}

+(NSString*)translateArab:(NSMutableString*)arab
{
    
    NSMutableString *Ms=[[NSMutableString alloc] init];
    NSMutableString *moneyStr=[[NSMutableString alloc] initWithString:arab];
    
    
    NSArray *MyBase=@[@"壹", @"贰", @"叁", @"肆", @"伍", @"陆", @"柒", @"捌", @"玖", @"拾", @"佰", @"仟", @"万", @"亿",@"点"];
    NSArray *MyScale=@[@"一", @"二", @"三", @"四", @"五", @"六", @"七", @"八", @"九", @"十", @"百", @"千", @"万", @"亿",@"点"];
    
    for (NSUInteger j=moneyStr.length;j>0;j--) {
        
        for (int i=0; i<MyScale.count; i++) {
            
            NSString *sty = [moneyStr substringWithRange:NSMakeRange(moneyStr.length-j, 1)];
            
            if ([sty isEqualToString:MyScale[i]]) {
                
                [Ms appendString:MyBase[i]];
            }
            
            
            
        }
        
        
        
    }
    
    
    NSString *final;
    
    if ([arab isEqualToString:@"〇"]) {
        
        final = @"零元";
    }
    else{
        final = [NSString stringWithFormat:@"%@元",Ms];
        
    }
    
    return final;
    
    
}

//- (NSString *)md5
//{
//    const char *cStr = [self UTF8String];
//    unsigned char digest[CC_MD5_DIGEST_LENGTH];
//    CC_MD5( cStr, (CC_LONG)strlen(cStr), digest );
//    
//    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
//    
//    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
//        [output appendFormat:@"%02x", digest[i]];
//    
//    return output;
//}

+ (NSString *)transformPinYinWithString:(NSString *)chinese
{
    NSString  * pinYinStr = [NSString string];
    if (chinese.length){
        NSMutableString * pinYin = [[NSMutableString alloc]initWithString:chinese];
        //1.先转换为带声调的拼音
        if(CFStringTransform((__bridge CFMutableStringRef)pinYin, NULL, kCFStringTransformMandarinLatin, NO)) {
            NSLog(@"带声调的pinyin: %@", pinYin);
        }
        //2.再转换为不带声调的拼音
        if (CFStringTransform((__bridge CFMutableStringRef)pinYin, NULL, kCFStringTransformStripDiacritics, NO)) {
            NSLog(@"不带声调的pinyin: %@", pinYin);
        }
        //3.去除掉首尾的空白字符和换行字符
        pinYinStr = [pinYin stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        //4.去除掉其它位置的空白字符和换行字符
        pinYinStr = [pinYinStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
        pinYinStr = [pinYinStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        pinYinStr = [pinYinStr stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSLog(@"去掉空白字符和换行字符的pinyin: %@", pinYinStr);
        [pinYinStr capitalizedString];
        
    }
    return pinYinStr;
}


+ (NSString *)md5:(NSString *)inPutText
{
    const char *cStr = [inPutText UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result);
    
    NSMutableString *md5Str = [NSMutableString string];
    for (int i = 0; i<16; i++) {
        [md5Str appendFormat:@"%02X",result[i]];
    }
    return [[md5Str lowercaseString] substringWithRange:NSMakeRange(8, 16)];
}

+(BOOL)istwoPoint:(NSString *)two
{
    NSString* mobile = @"^[0-9]+([.]{0}|[.]{1}[0-9]{0,2})$";
    NSPredicate *phoneNum = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mobile];
    
    if ([phoneNum evaluateWithObject:two] == YES) {
        return YES;
    } else {
        return NO;
    }
    
}

//返回 小时差 1位小数
+ (NSString *)gettimeIntervalSincepttrcTime:(NSString *)pttrcTime prtrcTime:(NSString *)prtrcTime
{
    NSDateFormatter *dateF = [NSDateFormatter new];
    dateF.dateFormat = @"yyyy-MM-dd HH:mm";
    
    NSDate *dateRent = [dateF dateFromString:pttrcTime];
    NSDate *dateReturn = [dateF dateFromString:prtrcTime];
    if(!dateRent || !dateReturn){
        NSDateFormatter *dateFss = [NSDateFormatter new];
        dateFss.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        dateRent = [dateFss dateFromString:pttrcTime];
        dateReturn = [dateFss dateFromString:prtrcTime];
    }
    
    if(!dateRent || !dateReturn){
        NSDateFormatter *dateFss = [NSDateFormatter new];
        dateFss.dateFormat = @"yyyy-MM-dd";
        dateRent = [dateFss dateFromString:pttrcTime];
        dateReturn = [dateFss dateFromString:prtrcTime];
    }
    
    
    dateF.dateFormat = @"yyyy-MM-dd HH:mm";
    double days = [dateReturn timeIntervalSinceDate:dateRent];
    days = days / 60 / 60;
    
    return [NSString stringWithFormat:@"%.1f", days];

}


//传入number 返回各种格式字符串
+ (NSString *)stringWithNumber:(NSNumberFormatterStyle)style number:(NSNumber *)number
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
    formatter.numberStyle = style;
    return [formatter stringFromNumber:number];
}


//获取ip地址
+ (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}

//- (NSString *)URLEncodedString
//{
//    NSString *encodedString = (NSString *)
//    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
//                                                              (CFStringRef)self,
//                                                              (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
//                                                              NULL,
//                                                              kCFStringEncodingUTF8));
//    return encodedString;
//}


+ (NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString
{
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}


- (NSString *)requestConfigTime
{
    return [NSString stringWithFormat:@"%@:00",self];
}

- (NSString *)setupDisplayTime
{
    if(self.length < 16) return self;
    return [self substringToIndex:16];
    
    
}

//返回字符串所占用的尺寸.
-(CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}



//判断手机号码格式是否正确
+ (BOOL)valiMobile:(NSString *)mobile
{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

- (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

//最新手机正则
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    if (mobileNum.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[0, 1, 6, 7, 8], 18[0-9]
     * 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
     * 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
     * 电信号段: 133,149,153,170,173,177,180,181,189
     */
//    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$";
    NSString *MOBILE = @"^[1][0-9][0-9]{9}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
     */
    NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[08]|8[2-478])\\d{8}$";
    /**
     * 中国联通：China Unicom
     * 130,131,132,145,155,156,170,171,175,176,185,186
     */
    NSString *CU = @"^1(3[0-2]|4[5]|5[56]|7[0156]|8[56])\\d{8}$";
    /**
     * 中国电信：China Telecom
     * 133,149,153,170,173,177,180,181,189
     */
    NSString *CT = @"^1(3[3]|4[9]|53|7[037]|8[019])\\d{8}$";
    
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//判断是否输入了emoji 表情
+ (BOOL)stringContainsEmoji:(NSString *)string{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                    
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }else if (hs == 0x200d){
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}


+ (BOOL)valiGunCode:(NSString *)gunCode
{
     gunCode = [gunCode stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (gunCode.length != 17)
    {
        return NO;
    }
    NSPredicate *gunCodePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"^\\d{17}$"];
    if (![gunCodePredicate evaluateWithObject:gunCode]){
        return NO;
    }
    return YES;
}

#pragma mark ***_车牌号正则_***
- (BOOL) validateCarNo:(NSString*)carNo
{
    //普通车牌
    NSString *carRegex1 =@"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    //绿色车牌
    NSString *carRegex2 =@"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{5}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex1];
    NSPredicate *carTest2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex2];

    //    NSLog(@"carTest is %@",carTest);
    if ([carTest1 evaluateWithObject:carNo] || [carTest2 evaluateWithObject:carNo]) {
        return YES;
    }else{
        return NO;
    }
}

/**
 *  转换为Base64编码
 */
- (NSString *)base64EncodedString;
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:0];
}

- (NSString *)base64DecodedString
{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:self options:0];
    return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}


/**
 *  金额字段加千位分隔符方法
 */
+ (NSString *)separatedDigitStringWithStr:(NSString *)digitString
{
    NSString *newStr;
    NSString *decimalStr;
    
    if ([digitString containsString:@"."]) {
        NSArray *strarray = [digitString componentsSeparatedByString:@"."];
        newStr = strarray[0];
        decimalStr = strarray[1];
    } else {
        newStr = digitString;
    }
    
    
    if (newStr.length <= 3) {
        return digitString;
    } else {
        NSMutableString *processString = [NSMutableString stringWithString:newStr];
        NSInteger location = processString.length - 3;
        NSMutableArray *processArray = [NSMutableArray array];
        while (location >= 0) {
            NSString *temp = [processString substringWithRange:NSMakeRange(location, 3)];
            [processArray addObject:temp];
            if (location < 3 && location > 0)
            {
                NSString *t = [processString substringWithRange:NSMakeRange(0, location)];
                [processArray addObject:t];
            }
            location -= 3;
        }
        NSMutableArray *resultsArray = [NSMutableArray array];
        int k = 0;
        for (NSString *str in processArray)
        {
            k++;
            NSMutableString *tmp = [NSMutableString stringWithString:str];
            if (str.length > 2 && k < processArray.count )
            {
                [tmp insertString:@"," atIndex:0];
                [resultsArray addObject:tmp];
            } else {
                [resultsArray addObject:tmp];
            }
        }
        NSMutableString *resultString = [NSMutableString string];
        for (NSInteger i = resultsArray.count - 1 ; i >= 0; i--)
        {
            NSString *tmp = [resultsArray objectAtIndex:i];
            [resultString appendString:tmp];
        }
        
        if (decimalStr) {
            return [NSString stringWithFormat:@"%@.%@",resultString,decimalStr];
        }else{
            return resultString;
        }
    }
}

+ (int)junc_CompareOneDateStr:(NSString *)oneDateStr withAnotherDateStr:(NSString *)anotherDateStr
{
    NSDate *dateA = [[NSDate alloc]init];
    NSDate *dateB = [[NSDate alloc]init];
    
    NSDateFormatter *dateF = [NSDateFormatter new];
    dateF.dateFormat = @"yyyy-MM-dd";
    
    dateA = [dateF dateFromString:oneDateStr];
    dateB = [dateF dateFromString:anotherDateStr];
    NSComparisonResult result = [dateA compare:dateB];
    if (result == NSOrderedAscending)
    {
        return 1;
        
    }else if (result == NSOrderedDescending)
    {
        return -1;
    }
    return 0;
}
+ (NSTimeInterval )dateTimeDifferenceWithStartTime:(NSString *)startTime endTime:(NSString *)endTime{
    NSDateFormatter *dateF = [NSDateFormatter new];
    dateF.dateFormat = @"yyyy-MM-dd HH:mm";
    NSDate *startD =[dateF dateFromString:startTime];
    NSDate *endD = [dateF dateFromString:endTime];
    NSTimeInterval start = [startD timeIntervalSince1970]*1;
    NSTimeInterval end = [endD timeIntervalSince1970]*1;
    NSTimeInterval value = end - start;
    return value;
}


+(NSString *)translationArabicNum:(NSInteger)arabicNum{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = kCFNumberFormatterRoundHalfDown;
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_Hans"];
    formatter.locale = locale;
    NSString *string = [formatter stringFromNumber:[NSNumber numberWithInteger:arabicNum]];
    return string;
}


//解密

+(NSString *)decryptUseDES:(NSData *)cipherData key:(NSString *)key{
//    NSData *encryptData = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
//    size_t plainTextBufferSize = [encryptData length];
//    const void *vplainText = [encryptData bytes];
//    CCCryptorStatus ccStatus;
//    uint8_t *bufferPtr = NULL;
//    size_t bufferPtrSize = 0;
//    size_t movedBytes = 0;
    
    
//    NSData* cipherData = [XuDes convertHexStrToData:[cipherText lowercaseString]];
    NSLog(@"++++++++///%@",cipherData);
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    size_t numBytesDecrypted = 0;
    NSString *testString = key;
    NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];
    Byte *iv = (Byte *)[testData bytes];
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, [key UTF8String], kCCKeySizeDES, iv, [cipherData bytes], [cipherData length], buffer, 1024, &numBytesDecrypted);
    NSString* plainText = nil;
    if (cryptStatus == kCCSuccess) {
        NSData* data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
        plainText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    return plainText;
}
@end
